# python image lib = PIL
# PIL只支持python2.7, 所以为了支持python3，创建了pillow，用于处理图像
# 缩放、切片、旋转、滤镜、输出文字、调色板等一应俱全。
# https://pillow.readthedocs.org/
import random

from PIL import Image, ImageFilter, ImageFont, ImageDraw

im: Image.Image = Image.open('arthas.png')
w, h = im.size
print(f'width: {w}, height: {h}')

# blur
im2 = im.filter(ImageFilter.BLUR)
im2.save('arthas_blur.jpg', 'jpeg')

# 缩放 // 取整
im.thumbnail(size=(w//2, h//2))
im.save('arthas_thumbnail.jpg', 'jpeg')


# 使用PIL创建图片验证码
rand_char = lambda: chr(random.randint(65, 90))  # 随机字符
rand_bg_color = lambda: (random.randint(64, 255), random.randint(64, 255), random.randint(64, 255))  # 随机背景颜色
rand_text_color = lambda: (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127))
i_width = 60 * 4
i_height = 60
im = Image.new('RGB', (i_width, i_height), (255, 255, 255))  # 创建一个白色图片
font = ImageFont.truetype('arial.ttf', 36)  # 创建字体, 查看支持的字体：os.listdir(os.path.join(os.environ.get("WINDIR"), "fonts"))
draw = ImageDraw.Draw(im)  # 创建画笔
# 随机填充背景色
for x in range(i_width):
    for y in range(i_height):
        draw.point((x, y), fill=rand_bg_color())
# 写入文字
for t in range(4):
    draw.text((60 * t + 10, 10), rand_char(), font=font, fill=rand_text_color())  # 字符每个宽10像素，
im2 = im.filter(ImageFilter.BLUR)
im.save('random_char.png', 'png')
